package handler

import (
	"net/http"

	"gitee.com/thewalkers/refactoring-code/model"
	"gitee.com/thewalkers/refactoring-code/model/apperrors"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
)

const (
	createPaymentSuccess = "创建收入成功"
	updatePaymentSuccess = "更新收入成功"
)

type createPaycheckParams struct {
	EmployeeID int64   `json:"employee_id" binding:"required"`
	GrossPay   float64 `json:"gross_pay" binding:"required"`
	NetPay     float64 `json:"net_pay" binding:"required"`
	Deduction  float64 `json:"deduction" binding:"required"`
}

func (h *Handler) CreatePayment(ctx *gin.Context) {
	var req createPaycheckParams

	if ok := bindData(ctx, &req); !ok {
		return
	}

	p := &model.Paycheck{
		EmployeeID: req.EmployeeID,
		GrossPay:   req.GrossPay,
		NetPay:     req.NetPay,
		Deduction:  req.Deduction,
	}

	if err := h.PaycheckService.Create(ctx, p); err != nil {
		zap.L().Error("server create paycheck failed", zap.Error(err))
		e := apperrors.NewInternal()
		ctx.JSON(e.Status(), gin.H{
			"error": e,
		})
		return
	}

	ctx.JSON(http.StatusOK, gin.H{
		"msg": createPaymentSuccess,
	})
}

type updatePaycheckParams struct {
	ID         int64   `json:"paycheck_id" binding:"required"`
	EmployeeID int64   `json:"employee_id" binding:"required"`
	GrossPay   float64 `json:"gross_pay" binding:"required"`
	NetPay     float64 `json:"net_pay" binding:"required"`
	Deduction  float64 `json:"deduction" binding:"required"`
}

func (h *Handler) UpdatePaycheck(ctx *gin.Context) {
	var req updatePaycheckParams

	if ok := bindData(ctx, &req); !ok {
		return
	}

	p := &model.Paycheck{
		ID:         req.ID,
		EmployeeID: req.EmployeeID,
		GrossPay:   req.GrossPay,
		NetPay:     req.NetPay,
		Deduction:  req.Deduction,
	}

	if err := h.PaycheckService.Update(ctx, p); err != nil {
		zap.L().Error("server update paycheck failed", zap.Error(err))
		e := apperrors.NewInternal()
		ctx.JSON(e.Status(), gin.H{
			"error": e,
		})
		return
	}

	ctx.JSON(http.StatusOK, gin.H{
		"msg": updatePaymentSuccess,
	})
}
